<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    label-width="120px"
    @submit.prevent="handleSubmit"
  >
    <slot name="default"></slot>
    
    <el-form-item>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
      <el-button @click="handleReset">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive,defineProps,defineEmits } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'

interface FormField {
  prop: string
  label: string
  required?: boolean
  component: any
  componentProps?: Record<string, any>
  rules?: FormRules
}

interface Props {
  fields: FormField[]
  initialData?: Record<string, any>
}

const props = defineProps<Props>()
const emit = defineEmits(['submit', 'reset'])

const formRef = ref<FormInstance>()
const formData = reactive(props.initialData || {})
const formRules = reactive<FormRules>({})

// 初始化表单规则
props.fields.forEach(field => {
  if (field.required) {
    formRules[field.prop] = [
      { required: true, message: `${field.label}不能为空`, trigger: 'blur' },
      ...(field.rules || [])
    ]
  } else if (field.rules) {
    formRules[field.prop] = field.rules
  }
})

const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    emit('submit', formData)
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const handleReset = () => {
  formRef.value?.resetFields()
  emit('reset')
}
</script>

<style scoped>
.el-form {
  max-width: 600px;
  margin: 0 auto;
}
</style>